package com.itcam.thread_;

/**
 * Author:Cammy.Wu
 * Date:2024-05-11
 * Description:
 */

/**
 * 同步代码块
 *  synchronized(锁对象){
 *      多条语句操作共享数据的代码
 *  }
 *  注意：锁对象可以是任意对象
 */
public class ThreadTest03 {
    /*
        需求：某电影院目前正在上映国产大片，共有100张票，而它有3个窗口卖票，请设计一个程序模拟该电影票卖票
                -- 多条线程共享操作同一份资源
     */
    public static void main(String[] args) {

        TicketTask3 t1 = new TicketTask3("窗口1");
        TicketTask3 t2 = new TicketTask3("窗口2");
        TicketTask3 t3 = new TicketTask3("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class TicketTask3 extends Thread{

    /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
     * {@code (null, null, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     */
    public TicketTask3() {
    }

    /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
     * {@code (null, null, name)}.
     *
     * @param name the name of the new thread
     */
    public TicketTask3(String name) {
        super(name);
    }

    private static int ticket=2000;

    @Override
    public void run() {
        while (true){
            synchronized (TicketTask3.class){ // 获取类的字节码对象
                if (ticket == 0) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
                ticket--;
            }
        }
    }
}
